/// 处理请求 的handler
use crate::db;
use crate::models::*;
use actix_web::{web, HttpResponse, Responder};
use deadpool_postgres::Pool;
use std::io::ErrorKind::Other;

pub async fn status() -> impl Responder {
    // "{\"status\": \"UP\"}"
    web::HttpResponse::Ok().json(Status {
        status: "UP".to_string(),
    })
}

pub async fn get_todos(db_pool: web::Data<Pool>) -> impl Responder {
    let client = db_pool
        .get()
        .await
        .expect("Error connecting to the database");

    let result = db::get_todos(&client).await;

    match result {
        Ok(todos) => HttpResponse::Ok().json(todos),
        Err(_) => HttpResponse::InternalServerError().into(),
    }
}

pub async fn get_items(db_pool: web::Data<Pool>, params: web::Path<(i32,)>) -> impl Responder {
    let client = db_pool
        .get()
        .await
        .expect("Error connecting to the database");

    let result = db::get_items(&client, params.0).await;

    match result {
        Ok(items) => HttpResponse::Ok().json(items),
        Err(_) => HttpResponse::InternalServerError().into(),
    }
}

// pub async fn create_todo(
//     db_pool: web::Data<Pool>,
//     json: web::Json<CreateTodoList>,
// ) -> impl Responder {
//     let client = db_pool
//         .get()
//         .await
//         .expect("Error connecting to the database");

//     let result = db::create_todo(&client, json.title.clone()).await;

//     match result {
//         Ok(todos) => HttpResponse::Ok().json(todos),
//         Err(_) => HttpResponse::InternalServerError().into(),
//     }
// }

pub async fn create_todo_temp(
    db_pool: web::Data<Pool>,
    params: web::Path<(String,)>,
) -> impl Responder {
    let client = db_pool
        .get()
        .await
        .expect("Error connecting to the database");

    let result = db::create_todo(&client, params.0.clone()).await;

    match result {
        Ok(todos) => HttpResponse::Ok().json(todos),
        Err(_) => HttpResponse::InternalServerError().into(),
    }
}

pub async fn check_item(db_pool: web::Data<Pool>, params: web::Path<(i32, i32)>) -> impl Responder {
    let client = db_pool
        .get()
        .await
        .expect("Error connecting to the database");

    let result = db::check_todo(&client, params.0, params.1).await;

    match result {
        Ok(_) => HttpResponse::Ok().json(ResultResponse { success: true }),
        Err(e) if e.kind() == Other => HttpResponse::Ok().json(ResultResponse { success: false }),
        Err(_) => HttpResponse::InternalServerError().into(),
    }
}
